package com.kun.hosp.service.impl;

import cn.hutool.core.bean.BeanUtil;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kun.commonutil.exception.HospitalException;
import com.kun.commonutil.hosputil.MD5;
import com.kun.commonutil.result.ResultCodeEnum;
import com.kun.hosp.feign.CmdFeignService;
import com.kun.hosp.repository.HospitalRepository;
import com.kun.hosp.service.HospitalService;
import com.kun.hosp.service.HospitalSetService;
import com.kun.model.entity.hosp.Hospital;
import com.kun.model.entity.hosp.HospitalSet;
import com.kun.model.entity.hosp.Schedule;
import com.kun.model.vo.hosp.HospitalQueryVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author zhoukun
 * @Date 2021/5/1 17:51
 */
@Service
@Slf4j
public class HospitalServiceImpl implements HospitalService {
    @Autowired
    private HospitalRepository hospitalRepository;

    @Autowired
    HospitalSetService hospitalSetService;

    @Autowired
    CmdFeignService cmdFeignService;

    /**
     * 上传医院信息
     *
     * @param paramMap
     */
    @Override
    public void save(Map<String, Object> paramMap) {
        //1.获取医院传递过来的签名，判断签名是否一致（MD5加密）
        HasSignKey(paramMap);
        //传输过程中“+”转换为了“ ”，因此我们要转换回来
        String logoDataString = (String)paramMap.get("logoData");
        if(!StrUtil.isEmpty(logoDataString)) {
            String logoData = logoDataString.replaceAll(" ", "+");
            paramMap.put("logoData", logoData);
        }
        //将map集合转hospital
        String param = JSONUtil.toJsonStr(paramMap);
        log.info("{}"+param);
//        JSONUtil.toBean(param, Hospital.class);
        Hospital hospital = JSON.parseObject(param, Hospital.class);
        log.info("{}"+hospital);
        //判断是否存在数据
        Hospital hospitalByHoscode = hospitalRepository.getHospitalByHoscode(hospital.getHoscode());
        //判断是否为空
        if (BeanUtil.isEmpty(hospitalByHoscode)){
            //添加
            hospital.setCreateTime(new Date());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            hospitalRepository.save(hospital);

        }else{
            //修改
            BeanUtil.copyProperties(hospital,hospitalByHoscode);
            hospitalByHoscode.setUpdateTime(new Date());
            hospitalByHoscode.setIsDeleted(0);
            hospitalRepository.save(hospitalByHoscode);
        }

    }

    /**
     * 查询医院
     *
     * @param hoscode
     * @return
     */
    @Override
    public Hospital getByHoscode(String hoscode) {

        return hospitalRepository.getHospitalByHoscode(hoscode);
    }

    /**
     * 判断签名
     * @param paramMap
     * @return
     */
    @Override
    public void HasSignKey(Map<String, Object> paramMap) {
        HospitalSet one = hospitalSetService.getOne(new QueryWrapper<HospitalSet>().eq("hoscode", paramMap.get("hoscode")));
        if(!(MD5.encrypt(one.getSignKey())).equals(paramMap.get("sign")))
        {
            throw new HospitalException(ResultCodeEnum.SIGN_ERROR);
        }
    }

    /**
     * admin医院查询
     *
     * @param page
     * @param limit
     * @param hospitalQueryVo
     * @return
     */
    @Override
    public Page<Hospital> selectPage(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {
        //创建Pageable 对象
        Sort sort=Sort.by(Sort.Direction.DESC,"createTime");
        Pageable pageable= PageRequest.of(page-1,limit,sort);
        Hospital hospital=new Hospital();
        BeanUtil.copyProperties(hospitalQueryVo,hospital);
        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写
        //创建实例
        Example<Hospital> example = Example.of(hospital, matcher);
        Page<Hospital> all = hospitalRepository.findAll(example, pageable);

        //获取查询list集合，遍历进行医院等级封装

        all.getContent().stream().forEach(item -> {
            this.setHospitalHosType(item);
        });
        return all;
    }

    /**
     * 更新上线状态
     *
     * @param id
     * @param status
     */
    @Override
    public void updateStatus(String id, Integer status) {
        if(status == 0 || status == 1) {
            Hospital hospital = hospitalRepository.findById(id).get();
            hospital.setStatus(status);
            hospital.setUpdateTime(new Date());
            hospitalRepository.save(hospital);
        }
    }

    /**
     * 医院详情
     *
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> show(String id) {
        Map<String, Object> result = new HashMap<>();

        Hospital hospital = hospitalRepository.findById(id).get();
        this.setHospitalHosType(hospital);
        //进行医院等级封装
        result.put("hospital", hospital);
        //医院预约信息
        result.put("bookingRule", hospital.getBookingRule());
//        //不需要重复返回
//        hospital.setBookingRule(null);
        log.info("{}"+hospital.getBookingRule());
        return result;
    }

    @Override
    public String getHospName(String hoscode) {
        return this.getByHoscode(hoscode).getHosname();
    }

    /**
     * 根据医院名称获取医院列表
     *
     * @param hosname
     * @return
     */
    @Override
    public List<Hospital> findByHosname(String hosname) {
        return hospitalRepository.findHospitalsByHosnameLike(hosname);
    }

    //获取查询list集合，遍历进行医院等级封装
    private Hospital setHospitalHosType(Hospital hospital) {
//        //根据dictCode和value获取医院等级名称
//        String hostypeString = cmdFeignService.getName("Hostype", hospital.getHostype());
//        //查询省 市  地区
//        String provinceString = cmdFeignService.getName(hospital.getProvinceCode());
//        String cityString = cmdFeignService.getName(hospital.getCityCode());
//        String districtString = cmdFeignService.getName(hospital.getDistrictCode());


        //查询等级,
        String hostypeString = cmdFeignService.getName(hospital.getHostype());
        String provinceString = cmdFeignService.getName(hospital.getProvinceCode());
        String cityString = cmdFeignService.getName(hospital.getCityCode());
        String districtString = cmdFeignService.getName(hospital.getDistrictCode());
        hospital.getParam().put("fullAddress",provinceString+cityString+districtString);

        hospital.getParam().put("hostypeString",hostypeString);
        return hospital;
    }

}
